package com.yonyou.pmclouds.task.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.yonyou.pmclouds.ApplicationConsts;
import com.yonyou.pmclouds.basecom.billstatus.BillStatusConst;
import com.yonyou.pmclouds.basecom.consts.BillTypeConst;
import com.yonyou.pmclouds.basecom.entity.PageObject;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.runtime.RuntimeEnvironment;
import com.yonyou.pmclouds.basecom.util.CommonFieldConst;
import com.yonyou.pmclouds.basecom.util.StorageFactory;
import com.yonyou.pmclouds.enterprise.entity.EnterpriseInfo;
import com.yonyou.pmclouds.outter.enterprise.EnterpriseInfoQuery;
import com.yonyou.pmclouds.outter.user.UserInfoQuery;
import com.yonyou.pmclouds.task.entity.TaskVO;
import com.yonyou.pmclouds.task.rmiitf.TaskQueryRemoteService;
import com.yonyou.pmclouds.task.util.TaskUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

import static com.yonyou.pmclouds.basecom.PMControllerConst.DEFAULT_PAGE_PAGE_START;

/**
 * 待办对外服务
 * 如果遇到需要对个性单据做特殊处理时，尽量不要在这个controller做。避免公用代码过度冗余
 *
 * @zhangwce
 */
@Controller
@RequestMapping({"/mobile/task","/task"})
public class TaskController {

	@Reference(version = ApplicationConsts.APPLICATION_VERSION)
	private TaskQueryRemoteService taskQueryService;
	@Autowired
	private UserInfoQuery userInfoQuery;
	@Autowired
	private EnterpriseInfoQuery enterpriseInfoQuery;
	@Autowired
	private TaskUtil taskUtil;
	@Autowired
	private StorageFactory storageFactory;

	@RequestMapping(value="/queryTodoTaskList")
	@ResponseBody
	public List<TaskVO> queryTodoTaskList(HttpServletRequest request) throws BusinessException {

		String pk_receiver = RuntimeEnvironment.getLoginUserId();
		List<TaskVO> resultTaskList = taskQueryService.queryTodoTaskList(pk_receiver);

		if(resultTaskList == null)
			return new ArrayList<>();

		fillUpPicInfo(resultTaskList, request);

		dealExtraInfo(resultTaskList);

		userInfoQuery.tranUserInfoField(resultTaskList.toArray(new TaskVO[0]),
				new String[]{TaskVO.PK_SENDER,TaskVO.PK_RECEIVER,TaskVO.TASKCREATOR},
				new String[]{TaskVO.SENDER_NAME,TaskVO.RECEIVER_NAME,TaskVO.TASKCREATOR_NAME});
		return resultTaskList;

	}

	/**
	 * 处理单据特性信息
	 *
	 * @param taskList
	 */
	private void dealExtraInfo(List<TaskVO> taskList){
		List<TaskVO> comAcceptTaskList = new ArrayList<>(); //存放综合验收单据的待办
		for(TaskVO vo : taskList){
			if (vo != null && BillTypeConst.COMPREHENSIVE_ACCEPTANCE_BILLTYPE.equals(vo.getSrc_bill_type())|| BillTypeConst.WORKSTART_BILLTYPE .equals(vo.getSrc_bill_type())) {
				comAcceptTaskList.add(vo);
			}
		}
		fillEnterpriseInfo(comAcceptTaskList);  //获取综合验收的施工单位名称
	}

	/**
	 * 根据图片名称从阿里获取路径
	 *
	 * @param taskList
	 */
	private void fillUpPicInfo(List<TaskVO> taskList, HttpServletRequest request){
		for (TaskVO taskVO : taskList){
			List<String> pictures =  taskVO.getPictures();
			if(pictures == null || pictures.size()<=0)
				continue;
			taskVO.setPicInfos(storageFactory.getStorageUtil().signForAppPics(pictures.toArray(new String[0]), request));
		}

	}

	/**
	 * 获取已处理任务列表
	 */
	@RequestMapping(value="/queryDoneTaskList")
	@ResponseBody
	public PageObject<?> queryDoneTaskList(
			@RequestParam(name = "pageStart", required = false, defaultValue = DEFAULT_PAGE_PAGE_START) String pageStart,
			@RequestParam(name = "pageSize", required = false, defaultValue = "1000") String pageSize) throws BusinessException {

		String pkReceiver = RuntimeEnvironment.getLoginUserId();
		List<TaskVO> resultTaskList = taskQueryService.queryDoneTaskListExceptReject(pkReceiver, Integer.valueOf(pageStart), Integer.valueOf(pageSize));

		if(resultTaskList == null || resultTaskList.size() == 0)
			return new PageObject<>(null, 0, Integer.valueOf(pageStart));

		dealExtraInfo(resultTaskList);

		userInfoQuery.tranUserInfoField(resultTaskList.toArray(new TaskVO[0]),
				new String[]{TaskVO.PK_SENDER,TaskVO.PK_RECEIVER,TaskVO.TASKCREATOR},
				new String[]{TaskVO.SENDER_NAME,TaskVO.RECEIVER_NAME,TaskVO.TASKCREATOR_NAME});

		getMessage(resultTaskList);
		return new PageObject<>(resultTaskList.toArray(new TaskVO[0]), resultTaskList.size(), Integer.valueOf(pageStart));

	}

	@RequestMapping(value="/queryOwnLaunchBills")
	@ResponseBody
	public TaskVO[] queryOwnLaunchBills(@RequestParam(name = "start") int start,
										@RequestParam(name = "size") int size) throws BusinessException {

		String task_creator = RuntimeEnvironment.getLoginUserId();
		List<TaskVO> resultTaskList = taskQueryService.queryOwnLaunchBills(task_creator,start,size);

		if(resultTaskList == null || resultTaskList.size() == 0)
			return new TaskVO[0];

		TaskVO[] ownLaunchVOs = resultTaskList.toArray(new TaskVO[0]);
		userInfoQuery.tranUserInfoField(ownLaunchVOs,
				new String[]{TaskVO.PK_SENDER,TaskVO.PK_RECEIVER},
				new String[]{TaskVO.SENDER_NAME,TaskVO.RECEIVER_NAME});
		return ownLaunchVOs;

	}
	/**
	 * 构造已处理任务列表的，提示消息。
	 */
	private void getMessage(List<TaskVO> taskList) throws BusinessException {
		if(taskList == null)
			return;
		//记录提交态taskVO
		Iterator<TaskVO> it = taskList.iterator();
		while (it.hasNext()) {
			TaskVO vo = it.next();
			if (vo == null || vo.getSrc_bill_type() == null)
				continue;
			if (BillStatusConst.COMMON_COMMIT_STATUS == vo.getBillstatus()) {
				//已处理待办列表不记录驳回再提交结束的待办
				it.remove();
				continue;
			}
			vo.setMessage(taskUtil.getTaskDescribe(vo));
		}
	}




	/**
	 * 如果TaskVO中的单据类型是综合验收时，billDescribe存放的是施工单位的主键，需要赋值为施工单位的名称
	 */
	private void fillEnterpriseInfo(List<TaskVO> taskList){
		if(taskList == null) return;

		Set<String> constructionUnitPks = new HashSet<>();
		//取到所有施工单位的pk, 获取施工单位信息
		for (TaskVO taskVO : taskList) {
			constructionUnitPks.add(taskVO.getBillDescribe());
		}
		Map<String, EnterpriseInfo> enterpriseInfoMap = enterpriseInfoQuery
				.queryEnterpriseByIds(constructionUnitPks.toArray(new String[0]));
		for (TaskVO taskVO : taskList) {
			EnterpriseInfo enterpriseInfo = enterpriseInfoMap.get(taskVO.getBillDescribe());
			if(enterpriseInfo == null)
				continue;
			taskVO.addProp(CommonFieldConst.ENTERPRISE_NAME,enterpriseInfo.getName());
		}
	}

}
